package com.mall.ultis;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.collections.map.HashedMap;

public class JwtHelper {
    private Long EXPIRATION_TIME;
    private String SECRET;
    private final String TOKEN_PREFIX = "Bearer";
    private final String HEADER_STRING = "Authorization";

    /**
     * 实例化jwt
     * @param secret
     * @param expire
     */
    public JwtHelper(String secret, long expire) {
        this.EXPIRATION_TIME = expire;
        this.SECRET = secret;
        System.out.println("正在初始化JwtHelper，expire=" + expire);
    }

    /**
     * 生成token
     * @param claims
     * @return string
     */
    public JSONObject generateToken(Map<String, Object> claims) {
        // 常用类
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.SECOND, EXPIRATION_TIME.intValue());

        Date date = calendar.getTime();
        String jwt = Jwts.builder()
                .setClaims(claims)
                .setExpiration(date)
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();

        JSONObject json = new JSONObject();

        json.put("token",TOKEN_PREFIX + " " + jwt);
        json.put("token-type", TOKEN_PREFIX);
        json.put("expire-time",new SimpleDateFormat("yyyy-MM-dd HH:ss:mm").format(date) );
        return json;
    }

    /**
     * 验证token
     * @param request
     * @return Map
     */
    public Map<String, Object> validateTokenAndGetClaims(HttpServletRequest request) {

        Map< String, Object > content = new HashMap< String, Object >();

        // 解析token
        try {
            String token = request.getHeader(HEADER_STRING);

            // 如果等于空
            if (token == null) {
                content.put( "status", 500 );
                content.put("msg", "jwt null");

                return content;
            }

            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody();
            content.put( "status", 200 );
            content.put("msg", "success");
            content.put("data", body);
            return content;
        } catch (Exception e) {
            content.put( "status", 500 );
            content.put("msg", e);
            return content;
        }

    }
}